package com.hyc.myvideo.ui.fragment.homefargment;

import android.content.Intent;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.acmenxd.toaster.Toaster;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.hyc.myvideo.R;
import com.hyc.myvideo.data.adapter.HomeClassExpandableListAdapter;
import com.hyc.myvideo.data.api.model.Banner;
import com.hyc.myvideo.data.api.model.BaseResult;
import com.hyc.myvideo.data.api.model.Home;
import com.hyc.myvideo.data.api.model.HomeClass;
import com.hyc.myvideo.data.api.model.HomeCourse;
import com.hyc.myvideo.data.api.model.Navigation;
import com.hyc.myvideo.ui.activity.home.AudioActivity;
import com.hyc.myvideo.ui.activity.home.ConfirmPurchaseActivity;
import com.hyc.myvideo.ui.activity.home.CourseActivity;
import com.hyc.myvideo.ui.activity.home.HomeDetailActivity;
import com.hyc.myvideo.ui.activity.home.LeavingMsgActivity;
import com.hyc.myvideo.ui.activity.home.TrainingActivity;
import com.hyc.myvideo.ui.activity.home.TrainingCatalogActivity;
import com.hyc.myvideo.ui.activity.home.VideoActivity;
import com.hyc.myvideo.ui.activity.my.LoginActivity;
import com.hyc.myvideo.ui.activity.my.RechargeActivity;
import com.hyc.myvideo.ui.base.BaseFragment;
import com.hyc.myvideo.utils.imguitl.NetworkImageHolderView;
import com.hyc.myvideo.widget.CommonExpandableListView;
import com.hyc.myvideo.widget.VIPsDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import timber.log.Timber;

/**
 * 首页
 *
 * @author gyb
 * @version 1.0
 * @created 2017/06/16
 */
public class HomeFragment extends BaseFragment {
    /**
     * 我的修炼
     */
    @BindView(R.id.fragment_home_head)
    ImageView mTraining;
    /**
     * 我的练习
     */
    @BindView(R.id.fragment_home_practice)
    ImageView mPractice;
    @BindView(R.id.fragment_home_pull_to_refresh)
    PullToRefreshScrollView pullToRefresh;

    private ConvenientBanner mBanner;
    /**
     * 国学
     */
    private TextView mChinese;
    /**
     * 禅修
     */
    private TextView mMeditation;
    /**
     * 养生
     */
    private TextView mHealth;
    /**
     * 留言
     */
    private TextView mMsg;
    /**
     * 导航
     */
    private LinearLayout mNav;

    private CommonExpandableListView expandableListView;

    /**
     * 导航 数据
     */
    private List<Navigation> navigationList;

    private List<HomeClass> homeClassList;
    private HomeClassExpandableListAdapter adapter;
    /**
     * 开通vip
     */
    private VIPsDialog viPsDialog;

    private List<String> networkImages;
    private String[] images = {
            "http://img2.imgtn.bdimg.com/it/u=3093785514,1341050958&fm=21&gp=0.jpg",
            "http://img2.3lian.com/2014/f2/37/d/40.jpg", "http://d.3987.com/sqmy_131219/001.jpg",
            "http://img2.3lian.com/2014/f2/37/d/39.jpg",
            "http://www.8kmm.com/UploadFiles/2012/8/201208140920132659.jpg",
            "http://f.hiphotos.baidu.com/image/h%3D200/sign=1478eb74d5a20cf45990f9df460b4b0c/d058ccbf6c81800a5422e5fdb43533fa838b4779.jpg",
            "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg"
    };

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.layout_fragment_home, null);
        mBanner = (ConvenientBanner) view.findViewById(R.id.layout_fragment_home_banner);
        mNav = (LinearLayout) view.findViewById(R.id.layout_fragment_home_nav);
        mChinese = (TextView) view.findViewById(R.id.layout_fragment_home_chinese);
        mMeditation = (TextView) view.findViewById(R.id.layout_fragment_home_meditation);
        mHealth = (TextView) view.findViewById(R.id.layout_fragment_home_health);
        mMsg = (TextView) view.findViewById(R.id.layout_fragment_home_msg);
        expandableListView =
                (CommonExpandableListView) view.findViewById(R.id.layout_fragment_home_elv);
        expandableListView.setFocusable(false);
        viPsDialog = new VIPsDialog(getContext());
        viPsDialog.setOnVIPsListener(new VIPsDialog.OnVIPsListener() {
            @Override
            public void toSure(int type) {
                startActivity(new Intent(getContext(), RechargeActivity.class));
            }
        });

        pullToRefresh.addView(view);
        pullToRefresh.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                api.getHomeList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            }
        });

        mTraining.setOnClickListener(click);
        mPractice.setOnClickListener(click);
        mChinese.setOnClickListener(click);
        mMeditation.setOnClickListener(click);
        mHealth.setOnClickListener(click);
        mMsg.setOnClickListener(click);

        homeClassList = new ArrayList<>();
        adapter = new HomeClassExpandableListAdapter(getContext(), homeClassList);
        expandableListView.setAdapter(adapter);

        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view,
                                        int groupPosition, long l) {
                Timber.e("===onGroupClick====" + groupPosition);
                return true;
            }
        });

        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view,
                                        int groupPosition, int childPosition, long l) {
                HomeCourse homeCourse = homeClassList.get(groupPosition).getList().get(childPosition);
                //1系列 2单个
                //系列进入系列列表再做判断，单个在本页面进行判断
                if (homeCourse.getState() == 1) {
                    startActivity(new Intent(getContext(), TrainingCatalogActivity.class).putExtra("id",
                            homeCourse.getId()));
                    return false;
                }

                if (userInfo.isLogin()) {
                    //user_vip_state 0=普通会员,1=vip会员,2=永久vip会员
                    //curriculum_charge_state  0=免费，1=vip,2=收费
                    switch (userInfo.getUser_vip_state()) {
                        case 0:
                            switch (homeCourse.getCurriculum_charge_state()) {
                                case 0:
                                    startAct(homeCourse);
                                    break;
                                case 1:
                                    viPsDialog.show();
                                    break;
                                case 2:
                                    // order_state  0未支付,1已经支付
                                    if (homeCourse.getOrder_state() == 0) {
                                        startActivity(
                                                new Intent(getContext(), ConfirmPurchaseActivity.class).putExtra("id",
                                                        homeCourse.getId()).putExtra("type", "3"));
                                    } else {
                                        startAct(homeCourse);
                                    }
                                    break;
                            }
                            break;
                        case 1:
                            //收费课程处理
                            if (homeCourse.getCurriculum_charge_state() == 2) {
                                // order_state  0未支付,1已经支付
                                if (homeCourse.getOrder_state() == 0) {
                                    startActivity(
                                            new Intent(getContext(), ConfirmPurchaseActivity.class).putExtra("id",
                                                    homeCourse.getId()).putExtra("type", "3"));
                                } else {
                                    startAct(homeCourse);
                                }
                            } else {
                                startAct(homeCourse);
                            }
                            break;
                        case 2:
                            startAct(homeCourse);
                            break;
                    }
                } else {
                    //未登录 免费课程 进入,其他进登录
                    //curriculum_charge_state  0=免费，1=vip,2=收费
                    switch (homeCourse.getCurriculum_charge_state()) {
                        case 0:
                            startAct(homeCourse);
                            break;
                        default:
                            startActivity(new Intent(getContext(), LoginActivity.class));
                            break;
                    }
                }

                //startAct(homeCourse);
                Timber.e("===onChildClick====" + groupPosition + "==childPosition=" + childPosition);
                return false;
            }
        });
    }

    /**
     * list的跳转
     */
    private void startAct(HomeCourse hCourse) {
        //1=视频,2=音频,3=图文
        switch (hCourse.getCurriculum_hour_type()) {
            case 1:
                startActivity(
                        new Intent(getContext(), VideoActivity.class).putExtra("id", hCourse.getId()));
                break;
            case 2:
                startActivity(
                        new Intent(getContext(), AudioActivity.class).putExtra("id", hCourse.getId()));
                break;
            case 3:
                startActivity(
                        new Intent(getActivity(), HomeDetailActivity.class).putExtra("id", hCourse.getId()));
                break;
        }
    }

    @Override
    protected void initData() {
        api.getHomeList();
    }

    private void setBanner() {
        //banner图
        networkImages = Arrays.asList(images);
        mBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, networkImages)
                .setPageIndicator(
                        new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        Toaster.show("==banner==" + position);
                    }
                });
    }

    @Override
    protected void onNexts(String result, String method) {

        BaseResult<Home> home = JSONObject.parseObject(result, new TypeReference<BaseResult<Home>>() {
        });
        if (home.isCode()) {
            List<Banner> banners = home.getResult().getBanner_list();
            navigationList = home.getResult().getNav_list();
            homeClassList.clear();
            homeClassList.addAll(home.getResult().getClass_list());
            homeClassList.addAll(home.getResult().getClass_list());
            homeClassList.addAll(home.getResult().getClass_list());
            homeClassList.addAll(home.getResult().getClass_list());
            homeClassList.addAll(home.getResult().getClass_list());
            homeClassList.addAll(home.getResult().getClass_list());
            homeClassList.addAll(home.getResult().getClass_list());

            for (int i = 0; i < homeClassList.size(); i++) {
                expandableListView.expandGroup(i);
                adapter.notifyDataSetChanged();
            }
            setBanner();
            setNav();
        } else {
            Toaster.show(home.getMsg());
        }

        if (pullToRefresh.isRefreshing()) {
            pullToRefresh.onRefreshComplete();
        }
    }

    @Override
    protected void onError() {
        if (pullToRefresh.isRefreshing()) {
            pullToRefresh.onRefreshComplete();
        }
    }

    /**
     * 设置导航
     */
    private void setNav() {
        if (navigationList != null && navigationList.size() == 3) {
            mChinese.setText(navigationList.get(0).getCurriculum_class_title());
            mMeditation.setText(navigationList.get(1).getCurriculum_class_title());
            mHealth.setText(navigationList.get(2).getCurriculum_class_title());
            mNav.setVisibility(View.VISIBLE);
        } else {
            mNav.setVisibility(View.GONE);
        }
    }

    View.OnClickListener click = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.fragment_home_head://修炼
                    LoginActivity.checkLogin(getActivity(), new LoginActivity.LoginCallback() {
                        @Override
                        public void onLogin() {
                            startActivity(new Intent(getActivity(), TrainingActivity.class));
                        }
                    });
                    break;
                case R.id.fragment_home_practice://练习
                    startActivity(new Intent(getActivity(), AudioActivity.class));
                    break;
                case R.id.layout_fragment_home_chinese://国学
                    startActivity(new Intent(getActivity(), CourseActivity.class).putExtra("id",
                            navigationList.get(0).getCurriculum_class_id())
                            .putExtra("title", navigationList.get(0).getCurriculum_class_title()));
                    break;
                case R.id.layout_fragment_home_meditation://禅修
                    startActivity(new Intent(getActivity(), CourseActivity.class).putExtra("id",
                            navigationList.get(1).getCurriculum_class_id())
                            .putExtra("title", navigationList.get(1).getCurriculum_class_title()));
                    break;
                case R.id.layout_fragment_home_health://养生
                    startActivity(new Intent(getActivity(), CourseActivity.class).putExtra("id",
                            navigationList.get(2).getCurriculum_class_id())
                            .putExtra("title", navigationList.get(2).getCurriculum_class_title()));
                    break;
                case R.id.layout_fragment_home_msg://留言
                    startActivity(new Intent(getActivity(), LeavingMsgActivity.class));
                    break;
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        mBanner.startTurning(3000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mBanner.stopTurning();
    }
}
